<template>
  <div class="home-container w-full flex flex-col items-center">
    <!-- 搜索栏 (居中+800px宽度) -->
    <div class="w-[800px] mx-auto p-3 bg-white sticky top-0 z-10 border-2 border-blue-500 rounded-lg">
      <div class="flex">
        <input
            type="text"
            v-model="searchQuery"
            placeholder="搜索想吃的店铺吧"
            @keyup.enter="filterRestaurants"
            class="flex-1 py-2 px-4 border border-gray-200 rounded-full text-sm"
        >
        <button
            @click="filterRestaurants"
            class="ml-2 px-5 bg-blue-500 text-white border-none rounded-full font-bold whitespace-nowrap"
        >
          搜索
        </button>
      </div>
    </div>

    <!-- 分类导航 (居中+800px宽度) -->
    <div class="w-[800px] mx-auto bg-white sticky top-16 z-10 p-3 border-2 border-blue-500 rounded-lg mt-2">
      <div class="flex overflow-x-auto gap-6 px-2 py-2">
        <button
            v-for="(category, index) in categories"
            :key="index"
            @click="activeCategory = category"
            class="flex flex-col items-center min-w-20 bg-transparent border-none p-1"
            :class="{ 'text-blue-500 font-bold': activeCategory === category }"
        >
          <img
              :src="getCategoryIcon(category)"
              :alt="category"
              class="w-12 h-12 object-contain mb-2"
          >
          <span class="text-sm text-gray-600">{{ category }}</span>
        </button>
      </div>
    </div>

    <!-- 商家列表 (居中+800px宽度) -->
    <div class="w-[800px] mx-auto mt-2">
      <RestaurantList :restaurants="filteredRestaurants"/>
    </div>

    <!-- 底部导航 (居中+800px宽度) -->
    <BottomNav />
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import {useRoute, useRouter} from 'vue-router'
import RestaurantList from '@/components/RestaurantList.vue'
import BottomNav from '@/components/BottomNav.vue'


import allIcon from '@/assets/images/categories/所有.png'
import fastfoodIcon from '@/assets/images/categories/蛋炒饭.png'
import bubbleteaIcon from '@/assets/images/categories/奶茶.png'
import bbqIcon from '@/assets/images/categories/烧烤.png'
import burgerIcon from '@/assets/images/categories/汉堡.png'
import noodlesIcon from '@/assets/images/categories/粥.png'
import hotpotIcon from '@/assets/images/categories/麻辣烫.png'
import fruitIcon from '@/assets/images/categories/山竹.png'
import breadIcon from '@/assets/images/categories/面包.png'

const router = useRouter()
const route = useRoute()
// 响应式数据
const searchQuery = ref('')
const activeCategory = ref('全部')
const categories = ref(['全部', '正餐快餐', '奶茶糕点', '烧烤小吃', '炸鸡汉堡', '粉面粥点', '冒菜辣烫', '水果', '面包'
])

const getCategoryIcon = (category) => {
  const iconMap = {
    '全部': allIcon,
    '正餐快餐': fastfoodIcon,
    '奶茶糕点': bubbleteaIcon,
    '烧烤小吃': bbqIcon,
    '炸鸡汉堡': burgerIcon,
    '粉面粥点': noodlesIcon,
    '冒菜辣烫': hotpotIcon,
    '水果': fruitIcon,
    '面包': breadIcon
  }
  return iconMap[category]
}

// 商家数据
const restaurants = ref([
      {
        id: 1,
        name: '蜜雪冰城',
        category: '奶茶糕点',
        image: new URL('@/assets/images/restaurants/1.jpg', import.meta.url).href,
        rating: 4.8,
        sales: '2200',
        status: '预订中',
        deliveryType: '可送上楼',
        dishes: [
          {
            name: '原味珍珠奶茶',
            price: '9.78',
            image: new URL('@/assets/images/dishes/1-0.jpg', import.meta.url).href
          },
          {
            name: '茉莉奶绿',
            price: '7.98',
            image: new URL('@/assets/images/dishes/1-1.jpg', import.meta.url).href
          },
          {
            name: '百香果果茶',
            price: '9.78',
            image: new URL('@/assets/images/dishes/1-2.jpg', import.meta.url).href
          }
        ],
        promotion: '满20减5'
      },
      {
        id: 2,
        name: '巴庄火锅',
        category: '冒菜辣烫',
        image: new URL('@/assets/images/restaurants/2.png', import.meta.url).href,
        rating: 4.8,
        sales: '2200',
        status: '预订中',
        deliveryType: '可送上楼',
        dishes: [
          {
            name: '番茄汤底',
            price: '15.00',
            image: new URL('@/assets/images/dishes/2-0.jpg', import.meta.url).href
          },
          {
            name: '鸭味杂套',
            price: '20.00',
            image: new URL('@/assets/images/dishes/2-1.jpg', import.meta.url).href
          },
          {
            name: '荤素煮食',
            price: '18.00',
            image: new URL('@/assets/images/dishes/2-2.jpg', import.meta.url).href
          }
        ],
        promotion: '满50减10'
      },

      {
        id: 3,
        name: '瓦香鸡米饭',
        category: '正餐快餐',
        image: new URL('@/assets/images/restaurants/3.jpg', import.meta.url).href,
        rating: 4.8,
        sales: '2200',
        status: '预订中',
        deliveryType: '可送上楼',
        dishes: [
          {
            name: '经典瓦香鸡米饭',
            price: '11',
            image: new URL('@/assets/images/dishes/3-0.jpg', import.meta.url).href
          },
          {
            name: '鸡肉煲汤饭',
            price: '15',
            image: new URL('@/assets/images/dishes/3-1.jpg', import.meta.url).href
          },
          {
            name: '藤椒凉鸡肉',
            price: '13',
            image: new URL('@/assets/images/dishes/3-2.gif', import.meta.url).href
          }
        ],
        promotion: '满20减5'
      },

      {
        id: 4,
        name: '海哥炒面',
        category: '粉面粥点',
        image: new URL('@/assets/images/restaurants/4.jpg', import.meta.url).href,
        rating: 4.8,
        sales: '2200',
        status: '预订中',
        deliveryType: '可送上楼',
        dishes: [
          {
            name: '火腿肠炒粉丝',
            price: '12.8',
            image: new URL('@/assets/images/dishes/4-0.jpg', import.meta.url).href
          },
          {
            name: '经典蛋粉丝',
            price: '8.0',
            image: new URL('@/assets/images/dishes/4-1.jpg', import.meta.url).href
          },
          {
            name: '黑酱油粉丝',
            price: '9.2',
            image: new URL('@/assets/images/dishes/4-2.jpg', import.meta.url).href
          }
        ],
        promotion: '满20减5'
      },
      {
        id: 5,
        name: '吃吧水果捞',
        category: '水果',
        image: new URL('@/assets/images/restaurants/5.jpg', import.meta.url).href,
        rating: 4.8,
        sales: '2200',
        status: '预订中',
        deliveryType: '可送上楼',
        dishes: [
          {
            name: '加酸奶',
            price: '1.2',
            image: new URL('@/assets/images/dishes/5-0.jpg', import.meta.url).href
          },
          {
            name: '加坚果碎',
            price: '2',
            image: new URL('@/assets/images/dishes/5-1.jpg', import.meta.url).href
          },
          {
            name: '加蜂蜜',
            price: '13',
            image: new URL('@/assets/images/dishes/5-2.jpg', import.meta.url).href
          }
        ],
        promotion: '满20减5'
      },
      {
        id: 6,
        name: '重庆小面',
        category: '粉面粥点',
        image: new URL('@/assets/images/restaurants/6.jpg', import.meta.url).href,
        rating: 4.8,
        sales: '2200',
        status: '预订中',
        deliveryType: '可送上楼',
        dishes: [
          {
            name: '红烧牛肉面',
            price: '15',
            image: new URL('@/assets/images/dishes/6-0.jpg', import.meta.url).href
          },
          {
            name: '卤猪蹄红汤面',
            price: '22.3',
            image: new URL('@/assets/images/dishes/6-1.jpg', import.meta.url).href
          },
          {
            name: '猪肉汤辣面',
            price: '12.3',
            image: new URL('@/assets/images/dishes/6-2.jpg', import.meta.url).href
          }
        ],
        promotion: '满20减5'
      },
      {
        id: 7,
        name: '帽牌货冒菜',
        category: '冒菜辣烫',
        image: new URL('@/assets/images/restaurants/7.jpg', import.meta.url).href,
        rating: 4.8,
        sales: '2200',
        status: '预订中',
        deliveryType: '可送上楼',
        dishes: [
          {
            name: '加午餐肉',
            price: '4',
            image: new URL('@/assets/images/dishes/7-0.jpg', import.meta.url).href
          },
          {
            name: '加鸡胸肉',
            price: '6.8',
            image: new URL('@/assets/images/dishes/7-1.png', import.meta.url).href
          },
          {
            name: '只吃素套餐',
            price: '7.5',
            image: new URL('@/assets/images/dishes/7-2.jpg', import.meta.url).href
          }
        ],
        promotion: '满20减5'
      },
      {
        id: 8,
        name: '华莱士',
        category: '炸鸡汉堡',
        image: new URL('@/assets/images/restaurants/8.jpg', import.meta.url).href,
        rating: 4.8,
        sales: '2200',
        status: '预订中',
        deliveryType: '可送上楼',
        dishes: [
          {
            name: '单人优惠套餐',
            price: '11.2',
            image: new URL('@/assets/images/dishes/8-0.png', import.meta.url).href
          },
          {
            name: '超级联动萌宠套餐',
            price: '32.5',
            image: new URL('@/assets/images/dishes/8-1.jpg', import.meta.url).href
          },
          {
            name: '六一儿童套餐（小份）',
            price: '15',
            image: new URL('@/assets/images/dishes/8-2.jpg', import.meta.url).href
          }
        ],
        promotion: '满20减5'
      },
      {
        id: 9,
        name: '稿定面包房',
        category: '面包',
        image: new URL('@/assets/images/restaurants/9.jpg', import.meta.url).href,
        rating: 4.8,
        sales: '2200',
        status: '预订中',
        deliveryType: '可送上楼',
        dishes: [
          {
            name: '菠萝大面包',
            price: '5',
            image: new URL('@/assets/images/dishes/9-0.jpg', import.meta.url).href
          },
          {
            name: '奶油牛角包',
            price: '12',
            image: new URL('@/assets/images/dishes/9-1.jpg', import.meta.url).href
          },
          {
            name: '土司方块',
            price: '8.9',
            image: new URL('@/assets/images/dishes/9-2.jpg', import.meta.url).href
          }
        ]
      }
      // 剩余商家按照相同模式转换...
    ]
        .map(restaurant => {
          // 计算人均价格：菜品单价之和/菜品种类数
          const total = restaurant.dishes.reduce((sum, dish) => sum + parseFloat(dish.price), 0)
          const avgPrice = (total / restaurant.dishes.length).toFixed(2)
          return {
            ...restaurant,
            avgPrice // 覆盖原有的avgPrice
          }
        })
)

// 新增订单按钮点击处理
const handleOrdersClick = () => {
  if (localStorage.getItem('authToken')) {
    router.push('/orders')
  } else {
    router.push('/login?redirect=/orders')
  }
}

// 计算属性
const filteredRestaurants = computed(() => {
  return restaurants.value.filter(restaurant => {
    const matchesCategory = activeCategory.value === '全部' ||
        restaurant.category === activeCategory.value
    const matchesSearch = searchQuery.value === '' ||
        restaurant.name.includes(searchQuery.value) ||
        restaurant.dishes.some(dish =>
            dish.name.includes(searchQuery.value))
    return matchesCategory && matchesSearch
  })
})

// 计算每个商家的人均价格
const processedRestaurants = computed(() => {
  return restaurantData.restaurants.map(r => {
    const total = r.dishes?.reduce((sum, dish) => sum + parseFloat(dish.price), 0) || 0
    const count = r.dishes?.length || 1
    return {
      ...r,
      computedAvgPrice: (total / count).toFixed(2)
    }
  })
})

// 方法
const filterRestaurants = () => {
  // 搜索逻辑已由计算属性处理
}

</script>

<style scoped>
/* 全局容器 */
.home-container {
  @apply max-w-[600px] mx-auto bg-[#f5f5f5] min-h-screen pb-[60px];
}

/* 搜索栏 */
.search-bar {
  @apply flex p-4 bg-white sticky top-0 z-20;
}
.search-bar input {
  @apply flex-1 p-3 border border-gray-100 rounded-full text-sm;
}
.search-bar button {
  @apply ml-4 px-5 py-0 bg-[#2395ff] text-white border-none rounded-full font-bold;
}

/* 分类导航（图标+文字） */
.category-nav {
  @apply bg-white p-4 sticky top-[60px] z-10;
}
.scroll-wrap {
  @apply flex overflow-x-auto px-4 gap-5;
}
.category-btn {
  @apply flex flex-col items-center min-w-[80px] bg-transparent border-none p-2 shrink-0;
}
.category-icon {
  @apply w-10 h-10 object-contain mb-2;
}
.category-btn span {
  @apply text-sm text-gray-600;
}
.category-btn.active span {
  @apply text-[#2395ff] font-bold;
}

.bottom-nav {
  @apply fixed bottom-0 left-0 right-0 flex justify-around bg-white p-3 shadow-[0_-2px_5px_rgba(0,0,0,0.1)] max-w-[600px] mx-auto;
}

.bottom-nav button {
  @apply text-xs text-gray-600 bg-transparent border-none;
}

.bottom-nav button.active {
  @apply text-[#2395ff];
}
</style>
